package ma.ensao.evalmetrics.view;

import java.awt.Color;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.List;

import ma.ensao.evalmetrics.controller.ResultManager;
import ma.ensao.evalmetrics.controller.StatManager;
import ma.ensao.evalmetrics.model.Result;
import ma.ensao.evalmetrics.model.Stat;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.CombinedDomainCategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.util.Rotation;

import com.opensymphony.xwork2.ActionSupport;

public class Stats extends ActionSupport {

	public Long id;
	private ResultManager resultmanager = new ResultManager();
	private StatManager statmanager = new StatManager();
	private Result result;
	private Result oldResult;
	private Stat stat;
	private Stat oldStat;
	private JFreeChart chart;

	public void param() throws NumberFormatException, IOException {

		File file = new File("list.txt");
		InputStream ips = new FileInputStream(file);
		InputStreamReader ipsr = new InputStreamReader(ips);
		BufferedReader br = new BufferedReader(ipsr);
		String ligne;
		int j = 0;
		while ((ligne = br.readLine()) != null) {
			System.out.println(ligne);
			if (j == 0) {
				id = (long) Integer.parseInt(ligne);
				System.out.println("mm" + id);
			}
			j++;
		}
		br.close();
		ipsr.close();
		ips.close();
		// file.delete();
	}

	public String execute() {
		File file = new File("list.txt");
		file.delete();
		FileWriter fw;
		try {

			fw = new FileWriter("list.txt", true);
			BufferedWriter bw = new BufferedWriter(fw);
			PrintWriter pw = new PrintWriter(bw);
			pw.print(getId());
			pw.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		result = resultmanager.LastResult(id);
		oldResult = resultmanager.beforeLast(id);
		stat = statmanager.LastStat(id);
		setOldStat(statmanager.beforeLast(id));

		return SUCCESS;

	}

	public String generalAF() {

		try {
			param();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		result = resultmanager.LastResult(id);
		List<Stat> statsListe = statmanager.MesStats(id);

		final String attributs = "Nombre d'attributs";
		final String files = "Nombre de fichiers";

		final DefaultCategoryDataset attributsSet = new DefaultCategoryDataset();
		final DefaultCategoryDataset attributsRateSet = new DefaultCategoryDataset();
		final DefaultCategoryDataset filesSet = new DefaultCategoryDataset();
		final DefaultCategoryDataset filesRateSet = new DefaultCategoryDataset();

		float num = 0;
		for (int i = 0; i < statsListe.size(); i++) {
			stat = statsListe.get(i);
			attributsSet.addValue(stat.getNbAtrributs(), attributs, "test "
					+ (i + 1));
			num += stat.getNbAtrributs();
			attributsRateSet.addValue(num / (i + 1), " Taux de " + attributs,
					"test " + (i + 1));
		}

		num = 0;
		for (int i = 0; i < statsListe.size(); i++) {
			stat = statsListe.get(i);
			filesSet.addValue(stat.getNbFiles(), files, "test " + (i + 1));
			num += stat.getNbFiles();
			filesRateSet.addValue(num / (i + 1), " Taux de " + files, "test "
					+ (i + 1));
		}

		final NumberAxis rangeAxis1 = new NumberAxis("Valeurs");
		rangeAxis1.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
		final BarRenderer renderer1 = new BarRenderer();
		renderer1.setSeriesPaint(0, Color.green);
		renderer1
				.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
		final CategoryPlot subplot1 = new CategoryPlot(attributsSet, null,
				rangeAxis1, renderer1);
		subplot1.setDomainGridlinesVisible(true);

		final ValueAxis axis2 = new NumberAxis("Taux");
		subplot1.setRangeAxis(1, axis2);
		subplot1.setDataset(1, attributsRateSet);
		subplot1.mapDatasetToRangeAxis(1, 1);
		final CategoryItemRenderer runrateRenderer1 = new LineAndShapeRenderer();
		runrateRenderer1.setSeriesPaint(0, Color.green);

		subplot1.setForegroundAlpha(0.7f);
		subplot1.setRenderer(0, renderer1);
		subplot1.setRenderer(1, runrateRenderer1);

		final NumberAxis rangeAxis2 = new NumberAxis("Valeurs");
		rangeAxis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
		final BarRenderer renderer2 = new BarRenderer();
		renderer2.setSeriesPaint(0, Color.yellow);
		renderer2
				.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
		final CategoryPlot subplot2 = new CategoryPlot(filesSet, null,
				rangeAxis2, renderer2);
		subplot2.setDomainGridlinesVisible(true);

		final ValueAxis axis3 = new NumberAxis("Taux");
		subplot2.setRangeAxis(1, axis3);
		subplot2.setDataset(1, filesRateSet);
		subplot2.mapDatasetToRangeAxis(1, 1);
		final CategoryItemRenderer runrateRenderer2 = new LineAndShapeRenderer();
		runrateRenderer2.setSeriesPaint(0, Color.yellow);

		subplot2.setForegroundAlpha(0.7f);
		subplot2.setRenderer(0, renderer2);
		subplot2.setRenderer(1, runrateRenderer2);

		final CategoryAxis domainAxis = new CategoryAxis("Tests");
		final CombinedDomainCategoryPlot plot = new CombinedDomainCategoryPlot(
				domainAxis);

		plot.add(subplot1, 1);
		plot.add(subplot2, 1);

		chart = new JFreeChart("Statistiques Générales", new Font("SansSerif",
				Font.BOLD, 12), plot, true);

		return SUCCESS;
	}

	public String generalMC() {

		try {
			param();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		result = resultmanager.LastResult(id);
		List<Stat> statsListe = statmanager.MesStats(id);

		final String classes = "Nombre de Classes";
		final String methods = "Nombre de Methodes";

		final DefaultCategoryDataset methodsSet = new DefaultCategoryDataset();
		final DefaultCategoryDataset methodsRateSet = new DefaultCategoryDataset();
		final DefaultCategoryDataset classesSet = new DefaultCategoryDataset();
		final DefaultCategoryDataset classesRateSet = new DefaultCategoryDataset();

		float num = 0;
		for (int i = 0; i < statsListe.size(); i++) {
			stat = statsListe.get(i);
			methodsSet
					.addValue(stat.getNbMethods(), methods, "test " + (i + 1));
			num += stat.getNbMethods();
			methodsRateSet.addValue(num / (i + 1), " Taux de " + methods,
					"test " + (i + 1));
		}

		num = 0;
		for (int i = 0; i < statsListe.size(); i++) {
			stat = statsListe.get(i);
			classesSet
					.addValue(stat.getNbClasses(), classes, "test " + (i + 1));
			num += stat.getNbClasses();
			classesRateSet.addValue(num / (i + 1), " Taux de " + classes,
					"test " + (i + 1));
		}

		final NumberAxis rangeAxis1 = new NumberAxis("Valeurs");
		rangeAxis1.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
		final BarRenderer renderer1 = new BarRenderer();
		renderer1.setSeriesPaint(0, Color.red);
		renderer1
				.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
		final CategoryPlot subplot1 = new CategoryPlot(methodsSet, null,
				rangeAxis1, renderer1);
		subplot1.setDomainGridlinesVisible(true);

		final ValueAxis axis2 = new NumberAxis("Taux");
		subplot1.setRangeAxis(1, axis2);
		subplot1.setDataset(1, methodsRateSet);
		subplot1.mapDatasetToRangeAxis(1, 1);
		final CategoryItemRenderer runrateRenderer1 = new LineAndShapeRenderer();
		runrateRenderer1.setSeriesPaint(0, Color.red);

		subplot1.setForegroundAlpha(0.7f);
		subplot1.setRenderer(0, renderer1);
		subplot1.setRenderer(1, runrateRenderer1);

		final NumberAxis rangeAxis2 = new NumberAxis("Valeurs");
		rangeAxis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
		final BarRenderer renderer2 = new BarRenderer();
		renderer2.setSeriesPaint(0, Color.blue);
		renderer2
				.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
		final CategoryPlot subplot2 = new CategoryPlot(classesSet, null,
				rangeAxis2, renderer2);
		subplot2.setDomainGridlinesVisible(true);

		final ValueAxis axis3 = new NumberAxis("Taux");
		subplot2.setRangeAxis(1, axis3);
		subplot2.setDataset(1, classesRateSet);
		subplot2.mapDatasetToRangeAxis(1, 1);
		final CategoryItemRenderer runrateRenderer2 = new LineAndShapeRenderer();
		runrateRenderer2.setSeriesPaint(0, Color.blue);

		subplot2.setForegroundAlpha(0.7f);
		subplot2.setRenderer(0, renderer2);
		subplot2.setRenderer(1, runrateRenderer2);

		final CategoryAxis domainAxis = new CategoryAxis("Tests");
		final CombinedDomainCategoryPlot plot = new CombinedDomainCategoryPlot(
				domainAxis);

		plot.add(subplot1, 1);
		plot.add(subplot2, 1);

		chart = new JFreeChart("Statistiques Générales", new Font("SansSerif",
				Font.BOLD, 12), plot, true);

		return SUCCESS;
	}

	public String methods() {

		try {
			param();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		stat = statmanager.LastStat(id);

		DefaultPieDataset dataset = new DefaultPieDataset();
		double total_methods = stat.getNbMHF() + stat.getNbMPF()
				+ stat.getNbMSF() + stat.getNbNPM();

		dataset.setValue(
				"Public = "
						+ new DecimalFormat("#.#").format(stat.getNbNPM()
								/ total_methods * 100) + "%", stat.getNbNPM()
						/ total_methods);
		dataset.setValue(
				"Static = "
						+ new DecimalFormat("#.#").format(stat.getNbMSF()
								/ total_methods * 100) + "%", stat.getNbMSF()
						/ total_methods);
		dataset.setValue(
				"Protected = "
						+ new DecimalFormat("#.#").format(stat.getNbMPF()
								/ total_methods * 100) + "%", stat.getNbMPF()
						/ total_methods);
		dataset.setValue(
				"Private = "
						+ new DecimalFormat("#.#").format(stat.getNbMHF()
								/ total_methods * 100) + "%", stat.getNbMHF()
						/ total_methods);

		/*
		 * chart = ChartFactory.createPieChart("Methods", // chart title
		 * dataset, // data true, // include legend true, false);
		 * 
		 * PiePlot plot = (PiePlot) chart.getPlot(); plot.setLabelFont(new
		 * Font("SansSerif", Font.PLAIN, 12));
		 * plot.setNoDataMessage("No data available"); plot.setCircular(false);
		 * plot.setLabelGap(0.02); plot.setBackgroundPaint(new Color(0xffffe0));
		 */
		chart = ChartFactory.createPieChart3D("Methods", // chart title
				dataset, // data
				true, // include legend
				true, false);

		PiePlot3D plot = (PiePlot3D) chart.getPlot();
		plot.setStartAngle(290);
		plot.setDirection(Rotation.CLOCKWISE);
		/*
		 * plot.setForegroundAlpha(0.5f);
		 * 
		 * chart.setBackgroundPaint(java.awt.Color.white);
		 */
		plot.setBackgroundPaint(new Color(255, 255, 255, 0));
		plot.setBackgroundImageAlpha(0.0f);
		chart.setBackgroundPaint(null);

		return SUCCESS;
	}

	public String lines() {

		try {
			param();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		result = resultmanager.LastResult(id);
		DefaultPieDataset dataset = new DefaultPieDataset();
		double total_lines = result.getCLOC() + result.getLOC();

		dataset.setValue(
				"LOC = "
						+ new DecimalFormat("#.#").format(result.getLOC()
								/ total_lines * 100) + "%", result.getLOC()
						/ total_lines);
		dataset.setValue(
				"CLOC = "
						+ new DecimalFormat("#.#").format(result.getCLOC()
								/ total_lines * 100) + "%", result.getCLOC()
						/ total_lines);

		chart = ChartFactory.createPieChart("Number of lines ", // chart title
				dataset, // data
				true, // include legend
				true, false);

		PiePlot plot = (PiePlot) chart.getPlot();
		plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
		plot.setNoDataMessage("No data available");
		plot.setCircular(false);
		plot.setLabelGap(0.02);
		plot.setBackgroundPaint(new Color(255, 255, 255, 0));
		plot.setBackgroundImageAlpha(0.0f);

		chart.setBackgroundPaint(null);

		return SUCCESS;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public JFreeChart getChart() {
		return chart;
	}

	public void setChart(JFreeChart chart) {
		this.chart = chart;
	}

	public Stat getStat() {
		return stat;
	}

	public void setStat(Stat stat) {
		this.stat = stat;
	}

	public Stat getOldStat() {
		return oldStat;
	}

	public void setOldStat(Stat oldStat) {
		this.oldStat = oldStat;
	}

	public Result getOldResult() {
		return oldResult;
	}

	public void setOldResult(Result oldResult) {
		this.oldResult = oldResult;
	}
}
